package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.ResquestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    private RestHighLevelClient restClient;
    @Override
    public PageResult list(ResquestParams param) {
//根据传入的关键字查询条件
        SearchRequest request = new SearchRequest("hotel");
//构建查询原对象
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        QueryBuilder functionScoreQueryBuilder = getQueryBuilder(param);
        //指定查询条件
        sourceBuilder.query(functionScoreQueryBuilder);
        if (!StringUtils.isEmpty(param.getKey())) {
            //指定高亮条件
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            //指定高亮字段
            highlightBuilder.field("all");
            //指定前缀后缀
            highlightBuilder.preTags("<em>");
            highlightBuilder.postTags("</em>");
            sourceBuilder.highlighter(highlightBuilder);
        }


        //分页查询
        int from=(param.getPage()-1)*param.getSize();
        sourceBuilder.from(from);
        sourceBuilder.size(param.getSize());
        //相关性算分,优先已分值排序
        sourceBuilder.sort("_score", SortOrder.DESC);
        //距离排序
        if (!StringUtils.isEmpty(param.getLocation())) {
            sourceBuilder.sort(SortBuilders.geoDistanceSort("location", new GeoPoint(param.getLocation()))
                    .order(SortOrder.ASC)
                    .unit(DistanceUnit.KILOMETERS));
        }

        //指定查询源
        request.source(sourceBuilder);

        try {
            SearchResponse response = restClient.search(request, RequestOptions.DEFAULT);
            //构建结果对象
            PageResult pageResult = new PageResult();
            //分析响应结果
            SearchHits searchHits = response.getHits();//第一层命中数据
            long total = searchHits.getTotalHits().value;//获取命中总数
            System.out.println("命中文档总数=" + total);
            pageResult.setTotal(total);
            List<HotelDoc> hotelDocList = new ArrayList<>();
            SearchHit[] hits = searchHits.getHits();//获取里层的数据hits
            //遍历hits
            for (SearchHit hit : hits) {
                String sourceAsString = hit.getSourceAsString();//获取文档中的JSON字符
                //将JSON转换为对象
                HotelDoc hotelDoc = JSON.parseObject(sourceAsString, HotelDoc.class);
                if (!StringUtils.isEmpty(param.getKey())) {
                    //获取高亮结果
                    String all = hit.getHighlightFields().get("all").fragments()[0].string();
                    //替换原始文档中的字段
                    hotelDoc.setName(all);
                }


                //获取距离
                Object[] sortValues = hit.getSortValues();
                if (sortValues.length>0) {
                    Object sortValue = sortValues[0];
                    hotelDoc.setDistance(sortValue);
                }
                hotelDocList.add(hotelDoc);
            }
            pageResult.setHotels(hotelDocList);
            return pageResult;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    //根据页面参数构建查询条件
    private QueryBuilder getQueryBuilder(ResquestParams param) {
        //构建查询条件
        QueryBuilder queryBuilder= QueryBuilders.boolQuery();
        //根据传入的关键字查询
        if (StringUtils.isEmpty(param.getKey())) {
            ((BoolQueryBuilder) queryBuilder).must(QueryBuilders.matchAllQuery()) ;
        }else {
            ((BoolQueryBuilder) queryBuilder).must(QueryBuilders.matchQuery("all", param.getKey())) ;
        }
        //添加过滤条件
        if (!StringUtils.isEmpty(param.getCity())) {
            ((BoolQueryBuilder) queryBuilder).filter(QueryBuilders.termQuery("city", param.getCity()));
        }
        if (!StringUtils.isEmpty(param.getBrand())) {
            ((BoolQueryBuilder) queryBuilder).filter(QueryBuilders.termQuery("brand", param.getBrand()));
        }
        if (!StringUtils.isEmpty(param.getStarName())) {
            ((BoolQueryBuilder) queryBuilder).filter(QueryBuilders.termQuery("starName",param.getStarName()));
        }
        if (param.getMinPrice()!=null) {
            ((BoolQueryBuilder) queryBuilder).filter(QueryBuilders.rangeQuery("price").gte(param.getMinPrice()));
        }
        if (param.getMaxPrice()!=null) {
            ((BoolQueryBuilder) queryBuilder).filter(QueryBuilders.rangeQuery("price").lte(param.getMaxPrice()));
        }
        //相关性算分
        return QueryBuilders.functionScoreQuery(queryBuilder, new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.termQuery("isAD", true),
                        ScoreFunctionBuilders.weightFactorFunction(10))//权重
        });
    }

    @Override
    public Map<String, List<String>> filters(ResquestParams params) {
        //返回过滤器数据
        Map<String, List<String>> map = new HashMap<>();
        List<String> city = new ArrayList<>();
        map.put("city", city);
        List<String> brand = new ArrayList<>();
        map.put("brand", brand);
        List<String> starName = new ArrayList<>();
        map.put("starName", starName);
        //添加聚合查询
        //构建查询对象,指定索引名
        SearchRequest request = new SearchRequest("hotel");
        //构建查询原对象
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //构建查询条件
        QueryBuilder queryBuilder;
        queryBuilder = getQueryBuilder(params);//查询所有
        //指定查询条件
        sourceBuilder.query(queryBuilder);
        //聚合查询
        AggregationBuilder agg = AggregationBuilders.terms("cityAgg");
        ((TermsAggregationBuilder) agg).field("city");
        sourceBuilder.aggregation(agg);
        AggregationBuilder starAgg = AggregationBuilders.terms("startNameAgg");
        ((TermsAggregationBuilder) starAgg).field("satrName");
        sourceBuilder.aggregation(starAgg);
        AggregationBuilder brandAgg = AggregationBuilders.terms("brandAgg");
        ((TermsAggregationBuilder) brandAgg).field("brand");
        sourceBuilder.aggregation(brandAgg);
        //不查原始文档
        sourceBuilder.size(0);
        //指定查询源
        request.source(sourceBuilder);
        //发送请求
        try {
            SearchResponse response = restClient.search(request, RequestOptions.DEFAULT);
            //分析结果
            Aggregations aggregations = response.getAggregations();
            Terms cityAgg= aggregations.get("cityAgg");
            for (Terms.Bucket bucket : cityAgg.getBuckets()) {
                String keyAsString = bucket.getKeyAsString();
                city.add(keyAsString);
            }
            Terms starNameAgg = aggregations.get("starName");
            for (Terms.Bucket bucket : starNameAgg.getBuckets()) {
                String keyAsString = bucket.getKeyAsString();
                starName.add(keyAsString);
            }
            Terms brandAgg1 = aggregations.get("brand");
            for (Terms.Bucket bucket : brandAgg1.getBuckets()) {
                String keyAsString = bucket.getKeyAsString();
                brand.add(keyAsString);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
